package com.hong.qrpc.resolver;

import com.hong.qrpc.constant.QrpcConst;
import com.hong.qrpc.header.Header;
import com.hong.qrpc.header.QrpcHeader;
import com.hong.qrpc.utils.ByteUtils;
import io.netty.buffer.ByteBuf;

/**
 * @Author HQT
 * @Date 2022/8/10 11:16
 */
public class QrpcResolver implements Resolver {
    @Override
    public byte[] toByteArr(Header header) {
        QrpcHeader qrpcHeader = (QrpcHeader) header;
        int version = QrpcConst.QRPC_VERSION;
        int serializationId = qrpcHeader.getSerializationType();
        long requestId = qrpcHeader.getRequestId();
        int dataLen = qrpcHeader.getDataLen();
        byte[] data = new byte[QrpcConst.HEADER_BYTE_LEN];
        int temp = 0;
        for (byte b : ByteUtils.numToBytes(2, version)) {
            data[temp++] = b;
        }
        for (byte b : ByteUtils.numToBytes(2, serializationId)) {
            data[temp++] = b;
        }
        for (byte b : ByteUtils.numToBytes(8, requestId)) {
            data[temp++] = b;
        }
        for (byte b : ByteUtils.numToBytes(4, dataLen)) {
            data[temp++] = b;
        }
        return data;
    }

    @Override
    public Header readHeader(ByteBuf in) {
        QrpcHeader qrpcHeader = new QrpcHeader();
        int version = in.readShort();
        int serializationId = in.readShort();
        long requestId = in.readLong();
        int dataLen = in.readInt();
        qrpcHeader.setVersion(version);
        qrpcHeader.setSerializationType(serializationId);
        qrpcHeader.setRequestId(requestId);
        qrpcHeader.setDataLen(dataLen);
        return qrpcHeader;
    }
}
